<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f1f1f1;
        }

        .login-container {
            width: 300px;
            padding: 2em;
            border-radius: 6px;
            box-shadow: 0 2px 9px rgba(0, 0, 0, 0.1);
            background-color: white;
        }

        h1 {
            text-align: center;
            margin-bottom: 1em;
        }

        form {
            display: flex;
            flex-direction: column;
            gap: 1em;
        }

        label {
            font-weight: bold;
        }

        input[type="text"],
        input[type="password"] {
            padding: 0.5em;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 1rem;
        }

        input:invalid {
            outline: none;
            box-shadow: 0 0 ¼em red;
        }

        button[type="submit"] {
            cursor: pointer;
            padding: 0.75em 1em;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 1rem;
            text-transform: uppercase;
            transition: background-color 0.2s ease-in-out;
        }

        button[type="submit"]:hover {
            background-color: #3e8e41;
        }
    </style>
</head>

<body>
    <div class="login-container">
        <h1>用户登录</h1>
        <form id="login-form" action="/login" method="post"> <label for="username">用户名:</label> <input type="text"
                id="username" name="username" pattern="^[a-zA-Z0-9._-]{3,}$" required
                title="请输入至少3个字符，只允许字母、数字、点、下划线和破折号">
            <label for="password">密码:</label>
            <input type="password" id="password" name="password" minlength="6" required title="请输入至少6个字符">
            
            <!-- 默认隐藏 -->
            <div id="error-message" class="error" style="display: none;">
                <p>登录失败，请检查用户名和密码是否正确。</p>
            </div>

            <button type="submit">登录</button>
            <button id="register-button" type="button" class="login-submit">注册</button>
        </form>
    </div>

    <script>
        const form = document.querySelector('#login-form');
        const errorMessage = document.getElementById('error-message');

        form.addEventListener('submit', async (event) => {
            event.preventDefault();

            // 检查是否有输入错误
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }

            // 清除之前的错误消息
            errorMessage.style.display = 'none';

            try {
                // 创建JSON对象，将表单数据转换为JSON格式
                const data = {
                    username: form.elements.username.value,
                    password: form.elements.password.value
                };

                const response = await fetch(form.action, {
                    method: form.method,
                    headers: {
                        'Content-Type': 'application/json' // 设置正确的Content-Type头
                    },
                    body: JSON.stringify(data) // 将JSON对象序列化为字符串作为请求主体
                });

                if (!response.ok) {
                    throw new Error('登录失败');
                }

                // 通常情况下，登录成功后服务器会返回一些有用的数据（如用户信息、JWT令牌等）
                // 根据您的后端接口文档，解析并使用这些数据
                const responseData = await response.json();

                // 登录成功，执行后续操作（如跳转到主页、存储用户信息等）
                alert('登录成功');
                form.reset();

                // 跳转到本地的index.html页面
                window.location.assign('./index.html');
            } catch (error) {
                alert(error);
                errorMessage.style.display = 'block';
                console.error('Login error:', error);
            }
        });

        // 为注册按钮添加点击事件监听器
        const registerButton = document.getElementById('register-button');
        registerButton.addEventListener('click', async () => {
            try {
                // 跳转到本地的register.html页面
                window.location.assign('./register.html');
            } catch (error) {
                console.error('Register error:', error);
                // 可以在此处添加错误提示或处理逻辑
            }
        });
    </script>
</body>

</html>